package com.gpscookie.redpanic;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

public class MainScreen extends Activity {
	private SensorManager sm;
	private SensorEventListener smListener;
	private int sensorType = Sensor.TYPE_ACCELEROMETER;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        smListener = new SensorEventListener() {        	

			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// TODO Auto-generated method stub				
			}

			public void onSensorChanged(SensorEvent event) {
				if (event == null || event.sensor == null || event.sensor.getType() != sensorType) {
					return;
				} else {
					float tmpx = event.values[1];
					float tmpy = event.values[0];
					setPlayer(tmpx, tmpy);
				}				
			}
			
			private void setPlayer(float accx, float accy) {
				World w = World.INSTANCE;
				float x = w.player.getX();
				float y = w.player.getY();
				x = x + accx*w.playerSpeed;
				y = y + accy*w.playerSpeed;
				if (x<0) x=0;
				if (x>w.width) x=w.width;
				if (y<0) y=0;
				if (y>w.height) y=w.height;
				w.player.setX(x);
				w.player.setY(y);
			}
        };
        
        sm.registerListener(smListener, sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_GAME);
        
        setContentView(new WorldView(this));
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	sm.unregisterListener(smListener);
    	World.INSTANCE.paused=true;
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	sm.registerListener(smListener, sm.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_GAME);
    	World.INSTANCE.paused=false;
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();    	
    }
    
    private class WorldView extends View {
    	Context context;
    	
		public WorldView(Context c) {
			super(c);
			context = c;
			World.INSTANCE.init(MainScreen.this, 0);
		}
    	
		@Override
		public boolean onTouchEvent (MotionEvent event) {
			World.INSTANCE.paused = !World.INSTANCE.paused;
			return false;
		}
		
        @Override 
        protected void onDraw(Canvas canvas) {        	
        	World w = World.INSTANCE;
        	w.width = canvas.getWidth();
        	w.height = canvas.getHeight();        	
        	w.render(canvas);
        	w.forward();
        	invalidate();
        }
    }
}